package com.ebelter.btcomlib.models.bluetooth.blueservices;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.ebelter.btcomlib.AppConfigs;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.bluetooth.products.scale.interfaces.IScaleMeasureCallback;
import com.ebelter.btcomlib.models.eventbus.CMDS;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IConnectStationCallback;
import com.ebelter.btcomlib.models.bluetooth.products.scale.ScaleConstant;
import com.ebelter.btcomlib.models.bluetooth.products.scale.ScaleManager;
import com.ebelter.btcomlib.utils.SpUtil;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class BlueBackRunService extends Service{
    private static final String TAG = "BlueBackRunService";

    public static List<ProductStyle> currentCouldConnectDevice;

    private MyMainHandle myMainHandle;

    private ScaleManager mScaleManager;



    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.i(TAG,"BlueBackRunService--onCreate()");
        inits();

    }

    private void inits() {
        currentCouldConnectDevice = new ArrayList<>();

        myMainHandle = new MyMainHandle(this);

        if (AppConfigs.SCALE_RUN_FLAG){
            LogUtils.i(TAG,"检测到--体脂秤--可以运行标志打开--准备初始化--initScale（）");
            initScale();
        }

        if (AppConfigs.BPM_RUN_FLAG){
            LogUtils.i(TAG,"检测到--血压计--可以运行标志打开--准备初始化--initBpm（）");
            initBpm();
        }

        if(AppConfigs.T_RUN_FLAG){
            LogUtils.i(TAG,"检测到--体温计--可以运行标志打开--准备初始化--initTemperature（）");
            initTemperture();
        }

        myMainHandle.sendEmptyMessageDelayed(WHAT_CHECK_BLUETOOTH_CONNECT_HEART,5000);//5秒开始检测的意思

    }

    //初始化体温计
    private void initTemperture() {
    }

    //初始化血压计
    private void initBpm() {}


    //初始化体脂秤秤
    private void initScale() {
        mScaleManager = new ScaleManager(this,300);

        mScaleManager.setBlueConnectStationCallback(new IConnectStationCallback() {
            @Override
            public void onConnected(ProductStyle productStyle,BluetoothDevice device) {

                //myMainHandle.sendEmptyMessageDelayed(WHAT_SCALE_SEND_HEART,0);

                CommonEventBus event=new CommonEventBus(TAG, "ScaleTestActivity", CMDS.UPDATE_BLUE_CONNECT_STATION,"已连接");
                EventBus.getDefault().post(event);

                sendLog2ScaleTestActivity(device.getAddress()+"--已连接");

                mScaleManager.getVersion();//下发版本信息
            }

            @Override
            public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {

            }


            @Override
            public void onDisConnected(ProductStyle productStyle) {
                //myMainHandle.removeMessages(WHAT_SCALE_SEND_HEART);
                CommonEventBus event=new CommonEventBus(TAG, "ScaleTestActivity", CMDS.UPDATE_BLUE_CONNECT_STATION,"已断开");
                EventBus.getDefault().post(event);
               // startScaleConnect();
                sendLog2ScaleTestActivity("-----设备断开了连接");

                mScaleManager.setUpdateFlag(false);

            }
        });

        mScaleManager.setmIMeasureResultCallback(new IScaleMeasureCallback() {

            @Override
            public void onScaleWake() {
                sendLog2ScaleTestActivity("-----设备醒屏");
            }

            @Override
            public void onScaleSleep() {
                sendLog2ScaleTestActivity("-----设备息屏");
            }

            @Override
            public void dealScaleResponse(int cmd, int position) {

            }

            @Override
            public void onReceiveMeasureResult(ScaleMeasureResult result) {}

            @Override
            public void onReceivedynamicMeasureResult(ScaleMeasureResult result) {

            }

            @Override
            public void onWeightOverLoad() {}

            @Override
            public void onReceiveHistoryRecord(ScaleMeasureResult result) {}

            @Override
            public void onFatMeasureError(int type) {}

            @Override
            public void onHistoryDownloadDone() {}

            @Override
            public void unitChange(String unit) {}

            @Override
            public void onLowPower() {
                ToastUtil.show("秤的电量低");}

            @Override
            public void setUserInfoSuccess() {}

            @Override
            public void receiveTime(long time) {}
        });

    }


    //发送消息给ScaleTestActivity界面
    private void sendLog2ScaleTestActivity(String log){
        CommonEventBus event=new CommonEventBus(TAG, "ScaleTestActivity", CMDS.LOG_ScaleTestActivity,log);
        EventBus.getDefault().post(event);
    }



    public class MyBinder extends Binder {
        public BlueBackRunService getServiceInstance(){
            return BlueBackRunService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.i(TAG,"BlueBackRunService--onBind()");
        return new MyBinder();
    }

    //开始体脂秤的连接
    public void startScaleConnect(){
        //01先判断是否绑定了体脂秤的地址
        String SCALE_BOND_DEVICE_ADDRESS = SpUtil.readString(ScaleConstant.SCALE_BOND_DEVICE_ADDRESS,null);
        if (TextUtils.isEmpty(SCALE_BOND_DEVICE_ADDRESS)){
            LogUtils.i(TAG,"App未绑定体脂秤地址，无法连接");
            return;
        }
        //把体脂秤加入到可以连接的设备中来
        boolean isContain = currentCouldConnectDevice.contains(ProductStyle.SCALE);
        if (!isContain){
            currentCouldConnectDevice.add(ProductStyle.SCALE);
        }

        boolean isContect = mScaleManager.isConnect();
        if (isContect){
            LogUtils.i(TAG,"体脂秤已经连接,无需重新连接");
            return;
        }
        LogUtils.i(TAG,"准备开始连接体脂秤");
        mScaleManager.connectDevice(SCALE_BOND_DEVICE_ADDRESS);
    }

    //获取体脂管理器
    public ScaleManager getScaleManage(){
        return mScaleManager;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.i(TAG,"BlueBackRunService---onDestroy()");
        exits();

    }

    private void exits() {

        if (currentCouldConnectDevice!=null){
            currentCouldConnectDevice.clear();
        }
        if (myMainHandle!=null){
            myMainHandle.removeCallbacksAndMessages(null);
        }

        if (mScaleManager!=null){
            mScaleManager.exit();//体脂秤退出
        }


    }

    /**检测蓝牙体脂秤的连接心跳包*/
    private static final int WHAT_CHECK_BLUETOOTH_CONNECT_HEART = 1;


    /**体脂秤的心跳包*/
    //private static final int WHAT_SCALE_SEND_HEART = 30;



    @SuppressLint("HandlerLeak")
    private class MyMainHandle  extends Handler{
        private WeakReference<Service> weakReference;

        MyMainHandle(Service service) {
            super(Looper.getMainLooper());
            this.weakReference = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference.get()==null){
                return;
            }
            int what=msg.what;

            if (WHAT_CHECK_BLUETOOTH_CONNECT_HEART==what){
                checkConnects();
            }



//            else if (WHAT_SCALE_SEND_HEART==what){//发送体脂秤的心跳包
//                //mScaleManager.sendHeartCheck();
//                sendEmptyMessageDelayed(WHAT_SCALE_SEND_HEART,1000);
//            }







        }


    }


    //检测连接
    private void checkConnects() {
        LogUtils.i(TAG,"checkConnects()---开始检测连接");
        myMainHandle.sendEmptyMessageDelayed(WHAT_CHECK_BLUETOOTH_CONNECT_HEART,5000);//5秒后重新去检测的意思

        if (currentCouldConnectDevice==null||currentCouldConnectDevice.size()==0){
            LogUtils.i(TAG,"checkConnects()---检测的集合里面没有要连接的设备");
            return;
        }

        if (currentCouldConnectDevice.contains(ProductStyle.SCALE)){
            checkScaleConnect();
        }
    }

    //检测--体脂秤--是否连接
    private void checkScaleConnect() {
        LogUtils.i(TAG,"checkScaleConnect()---开始检测--体脂秤--是否连接");
        String SCALE_BOND_DEVICE_ADDRESS = SpUtil.readString(ScaleConstant.SCALE_BOND_DEVICE_ADDRESS,null);
        if (TextUtils.isEmpty(SCALE_BOND_DEVICE_ADDRESS)){
            LogUtils.i(TAG,"checkScaleConnect()---App未绑定--体脂秤地址，无法连接,请先绑定体脂秤");
            mScaleManager.disConnect();
            return;
        }
        boolean isConnect = mScaleManager.isConnect();
        if (!isConnect){
            LogUtils.i(TAG,"checkScaleConnect()---检测到--体脂秤--没有连接中,准备重新连接");
            mScaleManager.connectDevice(SCALE_BOND_DEVICE_ADDRESS);
        }else {
            LogUtils.i(TAG,"checkScaleConnect()---检测到--体脂秤--连接中");
        }
    }
}
